<template>
  <div class="compact-container">
    <!-- Compact search row -->
    <div class="search-row">
      <span class="search-label">字典名称：</span>
      <el-input v-model="dict_name" size="small" class="search-input" disabled />
      <span class="search-label">字典标签：</span>
      <el-input v-model="dict_label" size="small" class="search-input" />
      <span class="search-label">数据状态：</span>
      <el-select v-model="status" size="small" placeholder="正常" class="status-select">
        <el-option label="正常" value="0" />
        <el-option label="停用" value="1" />
      </el-select>
      <el-button type="primary" size="small" @click="query">查询</el-button>
      <el-button size="small" @click="reset">重置</el-button>
      <el-button size="small" @click="retur">返回</el-button>
      <div class="flex-grow"></div>
      <el-button type="primary" size="small" @click="addEdit">新增</el-button>
    </div>

    <el-divider style="margin: 6px 0" />

    <!-- Compact table area -->
    <div class="table-wrapper">
      <el-table :data="tableData" border style="width: 100%" :cell-style="{ textAlign: 'center', padding: '4px 0' }"
        :header-cell-style="{
          textAlign: 'center',
          background: '#f5f7fa',
          fontWeight: 'bold',
          position: 'sticky',
          top: 0,
          padding: '4px 0',
          height: '36px'
        }">
        <el-table-column prop="dict_code" label="字典编码" width="100" />
        <el-table-column prop="dict_label" label="字典标签" width="200" />
        <el-table-column prop="dict_value" label="字典键值" width="100" />
        <el-table-column prop="dict_sort" label="字典排序" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            {{ scope.row.status == 0 ? "正常" : "停用" }}
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="create_time" label="创建时间" />
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <div class="action-group">
              <el-button size="small" @click="handleEdit(scope.row)">修改</el-button>
              <el-button size="small" type="danger" @click="handleDelete(scope.row.dict_code)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- Centered pagination -->
      <div class="pagination-center">
        <el-pagination small v-model:current-page="currentPage" v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]" :background="true" layout="total, sizes, prev, pager, next, jumper"
          :total="pageCount" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>

    <!-- Delete Confirmation Dialog -->
    <el-dialog v-model="dialogVisible1" width="385px" align-center>
      <template #header>
        <div class="dialog-header">删除确认</div>
      </template>
      <el-divider />
      <div class="dialog-content">
        确定删除该条字典信息吗？
      </div>
      <el-divider />
      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="close1">取消</el-button>
          <el-button type="danger" size="small" @click="del">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Dictionary Form Drawer -->
    <el-drawer v-model="dialogVisible2" :title="title" :direction="direction" size="30%" @close="close">
      <el-form ref="ruleFormRef" :model="data" label-width="80px" class="compact-form">
        <el-form-item prop="dict_label" label="字典标签">
          <el-input v-model="data.dict_label" placeholder="字典标签" />
        </el-form-item>

        <el-form-item prop="dict_value" label="字典键值">
          <el-input v-model="data.dict_value" placeholder="字典键值" />
        </el-form-item>

        <el-form-item prop="dict_type" label="字典类型">
          <el-input v-model="data.dict_type" placeholder="字典类型" disabled />
        </el-form-item>

        <el-form-item prop="dict_sort" label="字典排序">
          <el-input v-model="data.dict_sort" placeholder="字典排序" />
        </el-form-item>

        <el-form-item label="系统默认">
          <el-radio-group v-model="data.is_default">
            <el-radio value="Y">是</el-radio>
            <el-radio value="N">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="data.status">
            <el-radio value="0">正常</el-radio>
            <el-radio value="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item prop="remark" label="备注">
          <el-input v-model="data.remark" placeholder="备注" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button size="small" @click="close">取消</el-button>
          <el-button type="primary" size="small" @click="deptAdd">确定</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import dayjs from 'dayjs'
import { useStore } from 'vuex'

export default {
  setup() {
    const router = useRouter()
    const route = useRoute()
    const dict_name = ref("")
    const dict_label = ref("")
    // const dict_type = JSON.parse(route.query.rowData)
    const status = ref("0")
    const tableData = ref([])
    const currentPage = ref(1)
    const pageSize = ref(5)
    const pageCount = ref(0)
    const dialogVisible1 = ref(false)
    const dialogVisible2 = ref(false)
    const dict_code = ref("0")
    const title = ref("添加字典数据")
    const direction = ref('rtl')
    const store = useStore()
    const dict = store.state.dict;
    const data = reactive({
      dict_sort: "",
      dict_label: "",
      dict_type: dict,
      dict_value: "",
      is_default: "N",
      status: "0",
      remark: "",
      Create_by: localStorage.getItem('userLName'),
      Create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
      Update_by: localStorage.getItem('userLName'),
      Update_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
      Del_flag: "0",
    })

    onMounted(() => {
      fill()
      count()
      fill1()
    })

    function fill() {
      axios.get("http://localhost:5181/api/Dict/Getsys_Dict_DatasWhere", {
        params: {
          Dict_label: dict_label.value,
          Dict_type: dict,
          Status: status.value,
          currentPage: currentPage.value,
          pageSize: pageSize.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        tableData.value = result.data.map(item => ({
          ...item,
          create_time: formatDate(item.create_time)
        }))
      }).catch((err) => {
        console.error(err)
      })
    }

    function count() {
      axios.get("http://localhost:5181/api/Dict/Getsys_Dict_DatasCount", {
        params: {
          Dict_label: dict_label.value,
          Dict_type: dict,
          Status: status.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        pageCount.value = result.data
      }).catch((err) => {
        console.error(err)
      })
    }

    function fill1() {
      axios.get("http://localhost:5181/api/Dict/Getsys_Dict_TypesFyWhere", {
        params: {
          Dict_name: dict_name.value,
          Dict_type: dict,
          Status: status.value,
          currentPage: currentPage.value,
          pageSize: pageSize.value
        },
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        dict_name.value = result.data[0]?.dict_name || ""
      }).catch((err) => {
        console.error(err)
      })
    }

    function formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
    }

    function handleSizeChange(val) {
      pageSize.value = val
      fill()
    }

    function handleCurrentChange(val) {
      currentPage.value = val
      fill()
    }

    function query() {
      fill()
    }

    function reset() {
      dict_label.value = ""
      status.value = "0"
      fill()
    }

    function retur() {
      router.push('/main/Base_Manage/Dicttype')
    }

    function addEdit() {
      title.value = "添加字典数据"
      dialogVisible2.value = true
    }

    function close() {
      dialogVisible2.value = false
      data.dict_label = ""
      data.dict_value = ""
      data.dict_sort = ""
      data.is_default = "N"
      data.status = "0"
      data.remark = ""
      dict_code.value = "0"
    }

    function handleEdit(row) {
      title.value = "修改数据字典"
      dict_code.value = row.dict_code
      data.dict_label = row.dict_label
      data.dict_value = row.dict_value
      data.dict_sort = row.dict_sort
      data.is_default = row.is_default
      data.status = row.status
      data.remark = row.remark
      dialogVisible2.value = true
    }

    function handleDelete(id) {
      dialogVisible1.value = true
      dict_code.value = id
    }

    function del() {
      axios.put("http://localhost:5181/api/Dict/Putsys_Dict_DatasDelete", {
        dict_code: dict_code.value,
        Del_flag: "1"
      }, {
        headers: {
          authorization: `Bearer ${localStorage.getItem('token')}`
        }
      }).then((result) => {
        ElMessage.success('删除成功')
        dialogVisible1.value = false
        fill()
        close1()
      }).catch((err) => {
        ElMessage.error('删除失败')
        console.error(err)
      })
    }

    function close1() {
      dict_code.value = "0"
      dialogVisible1.value = false
    }

    function deptAdd() {
      if (dict_code.value === "0") {
        if (!data.dict_label || !data.dict_sort || !data.dict_value || !data.remark) {
          ElMessage.warning('请填写完整信息')
          return
        }

        axios.post("http://localhost:5181/api/Dict/Postsys_Dict_DatasAdd", {
          ...data
        }, {
          headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
          }
        }).then((result) => {
          ElMessage.success('添加成功')
          dialogVisible2.value = false
          fill()
          close()
        }).catch((err) => {
          ElMessage.error('添加失败')
          console.error(err)
        })
      } else {
        axios.put("http://localhost:5181/api/Dict/Putsys_Dict_DatasUpdate", {
          dict_code: dict_code.value,
          dict_label: data.dict_label,
          dict_value: data.dict_value,
          dict_sort: data.dict_sort,
          is_default: data.is_default,
          status: data.status,
          remark: data.remark,
          Update_by: data.Update_by,
          Update_time: data.Update_time
        }, {
          headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`
          }
        }).then((result) => {
          ElMessage.success('修改成功')
          dialogVisible2.value = false
          fill()
          close()
        }).catch((err) => {
          ElMessage.error('修改失败')
          console.error(err)
        })
      }
    }

    return {
      dict_name,
      dict_label,
      status,
      tableData,
      currentPage,
      pageSize,
      pageCount,
      dialogVisible1,
      dialogVisible2,
      data,
      title,
      direction,
      query,
      reset,
      retur,
      addEdit,
      handleEdit,
      handleDelete,
      handleSizeChange,
      handleCurrentChange,
      close1,
      close,
      del,
      deptAdd
    }
  }
}
</script>

<style scoped>
.compact-container {
  padding: 10px;
}

.search-row {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 6px;
  margin-top: -40px;
}

.search-label {
  white-space: nowrap;
  font-size: 13px;
}

.search-input {
  width: 160px !important;
}

.status-select {
  width: 160px !important;
}

.flex-grow {
  flex-grow: 1;
}

.table-wrapper {
  margin-top: 6px;
}

.pagination-center {
  display: flex;
  justify-content: center;
  margin-top: 10px;
}

.action-group {
  display: flex;
  justify-content: center;
  gap: 4px;
}

.dialog-header {
  font-size: 16px;
  font-weight: bold;
}

.dialog-content {
  padding: 10px 0;
  text-align: center;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.compact-form {
  padding: 20px;
}

:deep(.el-table__row) {
  height: 36px !important;
}

:deep(.el-table th.el-table__cell) {
  height: 36px !important;
}

:deep(.el-button--small) {
  padding: 5px 8px;
  height: 24px;
}
</style>